<?php


namespace app\shopConsole\service\category;

use app\dao\goods\CategoryDao;
use app\dao\goods\ShopCategoryDao;
use app\model\ShopCategory;

class CategoryService
{
    /**
     * @var ShopCategory
     */
    private ShopCategory $shopCategory;

    public function __construct(ShopCategory $shopCategory)
    {
        $this->shopCategory = $shopCategory ;
    }

    public function create($data)
    {
        $shopCategoryDao = new ShopCategoryDao();
        $level = $shopCategoryDao->getLevelByParentId($data['parent_id']);

        return $shopCategoryDao->save([
            'name' => $data['name'],
            'number' => $data['number'],
            'type' => $data['type'],
            'tags' => json_encode($data['tags']),
            'level' => empty($level->level) ? 1 : $level->level + 1,
            'ratio' => $data['ratio'],
            'parent_id' => $data['parent_id'],
            'shop_id' => $data['shop_id'],
        ]);
    }

    public function update($data)
    {
        $shopCategoryDao = new ShopCategoryDao();

        if (!empty($data['name']))
        {
            $this->shopCategory->name = $data['name'];
        }
        if (!empty($data['ratio']))
        {
            $this->shopCategory->ratio = $data['ratio'];
        }
        if (!empty($data['tags']))
        {
            $this->shopCategory->tags = json_encode($data['tags']);
        }
        $shopCategoryDao->update($this->shopCategory->toArray(), $this->shopCategory->id);

        return $shopCategoryDao->getById($this->shopCategory->id);
    }

    public function delete()
    {
        $shopCategoryDao = new ShopCategoryDao();
        $shopCategoryDao->deleteByid($this->shopCategory->id);
    }



}